import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:kq_flutter_widgets/widgets/save/save_model.dart';
import 'package:path_provider/path_provider.dart';

import '../../objectbox.g.dart';

class SaveManager {
  String saveKey;
  String filePath;
  String? dataJson;
  Store? store;
  Box<SaveModel>? box;
  late final String pathName;

  SaveManager(
      {required this.saveKey,
      required this.filePath,
      required VoidCallback openStoreSuccess,
      VoidCallback? openStoreError,
      this.dataJson,
      this.store}) {
    if (store == null) {
      openSelfStore(
          openStoreSuccess: openStoreSuccess, openStoreError: openStoreError);
      // getFileName(filePath).then((value) {
      //   pathName = value;
      //   store = openStore(directory: pathName);
      //   if (store != null) {
      //     box = store?.box<SaveModel>();
      //     openStoreSuccess();
      //   } else {
      //     if (openStoreError != null) {
      //       openStoreError();
      //     }
      //   }
      // });
    }
  }

  Future<String> getFileName(String fileName) async {
    //获取应用文件目录类似于Ios的NSDocumentDirectory和Android上的 AppData目录
    final fileDirectory = await getApplicationDocumentsDirectory();
    final filePath = fileDirectory.path;
    var file = Directory("$filePath/save");
    try {
      bool exists = await file.exists();
      if (!exists) {
        await file.create();
      }
    } catch (e) {
      print(e);
    }
    return "$filePath/save/$fileName";
  }

  //打开store
  openSelfStore({
    VoidCallback? openStoreSuccess,
    VoidCallback? openStoreError,
  }) {
    getFileName(filePath).then((value) {
      pathName = value;
      store = openStore(directory: pathName);
      if (store != null) {
        box = store?.box<SaveModel>();
        if (openStoreSuccess != null) {
          openStoreSuccess();
        }
      } else {
        if (openStoreError != null) {
          openStoreError();
        }
      }
    });
  }

  ///插入数据,key不传则默认传入当前的saveKey
  insertDataToObject(String data, {String? key}) {
    if (store != null) {
      box?.putAsync(SaveModel(pathKey: key ?? saveKey, jsonData: data));
    } else {
      openSelfStore(
        openStoreSuccess: () {
          box?.putAsync(SaveModel(pathKey: key ?? saveKey, jsonData: data));
        },
        openStoreError: () {
          //打开数据库失败
        },
      );
    }
  }

  ///删除数据,key不传则默认传入当前的saveKey
  removeDataToObject([String? key]) async {
    SaveModel? model = await searchDataFromObjet(key ?? saveKey);
    if (model != null) {
      box?.remove(model.id);
    } else {
      print('未查询到');
    }
  }

  ///删除ObjectBox中所有的数据
  removeAllDataToObject() {
    box?.removeAll();
  }

  ///查询数据,key不传则默认传入当前的saveKey
  Future<SaveModel?> searchDataFromObjet([String? key]) {
    Completer<SaveModel?> completer = Completer();
    if (store != null) {
      Query<SaveModel> query =
          box!.query(SaveModel_.pathKey.equals(key ?? saveKey)).build();
      SaveModel? model = query.findFirst();
      query.close();
      completer.complete(model);
    } else {
      openSelfStore(
        openStoreSuccess: () {
          Query<SaveModel> query =
              box!.query(SaveModel_.pathKey.equals(key ?? saveKey)).build();
          SaveModel? model = query.findFirst();
          query.close();
          completer.complete(model);
        },
        openStoreError: () {
          completer.complete(null);
        },
      );
    }
    return completer.future;
  }
}
